package com.atguigu.lease.web.admin.custom.interceptor;

//import com.atguigu.lease.common.context.LoginUser;
//import com.atguigu.lease.common.context.LoginUserContext;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器"+request.getRequestURI());
        String Token = request.getHeader("ACCESS_TOKEN");
        if (!StringUtils.hasText(Token)) {
            throw new RuntimeException("用户未登录");
        } else {
            Claims claims = JwtUtil.parseToken(Token);
            String username = claims.get("username", String.class);
            Long userId = claims.get("userId", Long.class);
            LoginUser loginUser = new LoginUser(userId, username);
            LoginUserContext.setLoginUser(loginUser);
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.removeLoginUser();
    }
}
